package cn.itsource.org.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.itsource.basic.other.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.User;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User, UserQuery> implements IUserService {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean checkPhone(String phone) {
        boolean mobile = Validator.isMobile(phone);
        if (!mobile) {
            throw new BusinessException("手机号有误,请重新输入...");
        }
        Example example = new Example(User.class);
        example.and().andEqualTo("phone", phone);
        User user = mapper.selectOneByExample(example);
        if (user != null) {
            throw new BusinessException("手机号已存在!");
        }
        return true;
    }

    @Override
    public boolean sendMobileCode(String phone, HttpServletRequest request) {
        //验证手机号
        boolean mobile = Validator.isMobile(phone);
        if (!mobile) {
            throw new BusinessException("手机号有误,请重新输入...");
        }

        String code = RandomUtil.randomNumbers(4);
        redisService.setStringKeyAndValue(phone, code, 2);
        log.info("[宠物乐园验证码]:{}", code);
        //SendMobileMessageUtil.sendMobileMessage(phone, code);
        return true;
    }

    @Override
    public boolean registerUser(User user) {
        checkPhone(user.getPhone());
        String code = redisService.getKeyStringValue(user.getPhone());
        if (code == null) {
            throw new BusinessException("验证码已过期!");
        }
        if (!code.equals(user.getCode())) {
            throw new BusinessException("验证码不正确!");
        }
        if (!user.getPassword().equals(user.getConfigPassword())) {
            throw new BusinessException("两次输入的密码不一致");
        }
        user.init();
        return mapper.insertSelective(user) > 0;
    }
}
